//获取data中的用户名和密码，并设置其格式
function formatParam(data) {
    let arr = []
    for (let key in data) {
        arr.push(`${key}=${data[key]}`)
    }
    return arr.join('&')
}

// 实例化ajax
function ajax(options) {
    // 创建XMLHttpRequest
    let xhr = new window.XMLHttpRequest()
    let params = formatParam(options.data)
    //将method转换为大写
    let method = options.method.toUpperCase()
    if (method == 'GET') {
        xhr.open(method, options.url + '?' + params)
        xhr.send()
    } else if (method == 'POST') {
        xhr.open(method, options.url)
        xhr.setRequestHeader('content-type', 'application/x-www.form-urlencoded')
        xhr.send(params)
    }

    // 响应数据处理
    xhr.onreadystatechange = function (e) {
        e = e || window.event
        let target = e.target || e.srcElement
        if (target.readyState === 4) {
            if (target.status === 200) {
                options.success(JSON.parse(target.responseText))
            } else {
                options.fail('网络错误' + target.status)
            }
        }
    }
}

/***
 * promise封装请求处理异步任务
 */
function myPromise(options) {
    return new Promise(function (resolve, reject) {
        ajax({
            method: options.method,
            url: options.url,
            data: options.data,
            success: function (res) {
                resolve(res)
            },
            fail: function (error) {
                reject(error)
            }
        })
    })
}